$(function() {
    // 倒计时
    var countdown = 6;
    var isClicked = false;
    var originalBgColor = $("#submit").css("background-color");
    $('#createImageForm').submit(function(event) {
        event.preventDefault();
        if (!isClicked) {
            isClicked = true;
            $("#submit").css("background-color", "gray");
            $("#submit").prop("disabled", true);
            // 开启定时器
            var countdownInterval = setInterval(function() {
                countdown--; // 每秒减少1秒
                $("#submit").text(countdown + "秒后可再次点击");
                if (countdown == 0) {
                    // 清除定时器
                    clearInterval(countdownInterval);
                    // 重新初始化倒计时
                    countdown = 6;
                    // 恢复默认效果
                    $("#submit").css("background-color", originalBgColor);
                    $("#submit").text("生成图片");
                    $("#submit").prop("disabled", false);
                    isClicked = false;
                }
            }, 2000);
        }

        var form = $(this);
        var prompt = form.find('#prompt').val();
        var size =  $('input[name="size"]:checked').val();
        $.ajax({
            type: 'POST',
            url: 'openai-request.php',
            data: {
                prompt: prompt,
                size: size
            },
            success: function(response) {
                var newObj = JSON.parse(response);
                var imgUrl = newObj.data[0].url;
                $('#imageContainer').html('<img src="' + imgUrl + '">');
            },
            error: function(xhr, status, error) {
                console.log(error);
            }
        });
    });
});